<?php

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

/**
 * 京东联盟订单 每天凌晨4:00更新一次 biz-admin 机器
 */
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\tools\JdUnion;
use Doraemon\tools\Curl;
use Doraemon\tools\Log;

$startTime = $argv[1] ?? date('Y-m-d H:i:s', strtotime("-1 days", strtotime(date('Y-m-d'))));
$endTime = $argv[2] ?? date('Y-m-d H:i:s', strtotime($startTime) + 86399);

run($startTime, $endTime, 1);//按下单时间查询
run($startTime, $endTime, 3);//按更新时间查询

function run($startTime, $endTime, $type)
{
    $start = strtotime($startTime);
    do {
        $end = $start + 3600;
        $end = ($end <= strtotime($endTime)) ? $end : strtotime($endTime);
        $page = 1;
        getOrder($start, $end, $page, $type);
        $start = $start + 3600;
    } while ($start <= $end);
}

function getOrder($start, $end, $page = 1, $type = 1)
{
    $startTime = date('Y-m-d H:i:s', $start);
    $endTime = date('Y-m-d H:i:s', $end);
    $res = JdUnion::getOrder($startTime, $endTime, $page, $type, 400);
    var_dump('查询订单#type:' . $type . '#page:' . $page . '#start:' . $startTime . '#end:' . $endTime);
    $hasMore = false;
    if ($res && $res['code'] == 200 && isset($res['data']) && $res['data']) {
        var_dump('count:' . count($res['data']));
        if ($res['hasMore']) {
            $page = $page + 1;
            $hasMore = true;
        }
        foreach ($res['data'] as $row) {
            sendData($row);
        }
    }
    if ($hasMore) {
        getOrder($start, $end, $page, $type);
    }
}

function sendData($row)
{
    $url = 'http://logcollector.hhzbi.com/v1/text/rebate_order_data';
    $params = [
        'body' => json_encode(['type' => 2, 'data' => $row]),
        'headers' => [
            'Accept' => 'text/plain;charset=utf-8',
            'Content-Type' => 'application/json; charset=utf-8',
        ]
    ];
    $result = Curl::Request('POST', $url, $params);
    if ($result['httpCode'] != 200 || $result['code'] != 1) {
        Log::debug('发送数据失败#' . $url, $result);
    }
}





